package com.shqcjd.yunweiyanoperator.wxapi;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import com.shqcjd.yunweiyanoperator.api.ApiService;
import com.shqcjd.yunweiyanoperator.helper.rxjavahelper.RxObserver;
import com.shqcjd.yunweiyanoperator.helper.rxjavahelper.RxSchedulersHelper;
import com.shqcjd.yunweiyanoperator.model.ResponseData;
import com.shqcjd.yunweiyanoperator.model.eventbus.CompanyRegisterSuccessEvebt;
import com.shqcjd.yunweiyanoperator.model.eventbus.WechatLoginEvent;
import com.shqcjd.yunweiyanoperator.model.pojo.VideoCategory;
import com.shqcjd.yunweiyanoperator.ui.activity.LoginActivity;
import com.shqcjd.yunweiyanoperator.util.ToastUtils;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.List;

import io.reactivex.disposables.Disposable;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class WXEntryActivity extends Activity implements IWXAPIEventHandler {

    private IWXAPI api;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        api = WXAPIFactory.createWXAPI(this, "wx071d628d24dc00d9", false);
        api.handleIntent(getIntent(), this);
        LoginActivity.wechatOpenid = "";
        LoginActivity.wechatName = "";
    }

    @Override
    public void onReq(BaseReq baseReq) {

    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        api.handleIntent(intent, this);
    }


    @Override
    public void onResp(BaseResp baseResp) {
        switch (baseResp.errCode) {
            case BaseResp.ErrCode.ERR_OK:
                String code = ((SendAuth.Resp) baseResp).code;
                //获取accesstoken
                Log.d("tou", code.toString()+ "-");
                getAccessToken(code);
//                getVodepCategoryHttp(code);
                break;
            case BaseResp.ErrCode.ERR_AUTH_DENIED://用户拒绝授权
                finish();
                break;
            case BaseResp.ErrCode.ERR_USER_CANCEL://用户取消
                finish();
                break;
            default:
                finish();
                break;
        }
    }

    private void getAccessToken(String code) {
        //获取授权
        StringBuffer loginUrl = new StringBuffer();
        loginUrl.append("https://api.weixin.qq.com/sns/oauth2/access_token")
                .append("?appid=")
                .append("wx071d628d24dc00d9")
                .append("&secret=")
                .append("925eb41e649d0184ae2e5d51e621d357")
                .append("&code=")
                .append(code)
                .append("&grant_type=authorization_code");

        OkHttpClient okHttpClient = new OkHttpClient();
        final Request request = new Request.Builder()
                .url(loginUrl.toString())
                .get()//默认就是GET请求，可以不写
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("tou", e.toString());
                ToastUtils.showShort(WXEntryActivity.this, e.toString());
                finish();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String responseInfo= response.body().string();
                Log.d("tou", "onResponse: " +responseInfo);
                String access = null;
                String openId = null;
                try {
                    JSONObject jsonObject = new JSONObject(responseInfo);
                    access = jsonObject.getString("access_token");
                    openId = jsonObject.getString("openid");
                    getUserInfo(access, openId);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }


    private void getUserInfo(String access, String openid) {
        String getUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" + access + "&openid=" + openid;
        OkHttpClient okHttpClient = new OkHttpClient();
        final Request request = new Request.Builder()
                .url(getUserInfoUrl)
                .get()//默认就是GET请求，可以不写
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d("tou", "onFailure: ");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String responseInfo= response.body().string();
                Log.d("tou", "onResponse: " + responseInfo);
                JSONObject jsonObject = null;
                String nickname = "";
                String openid = "";
                try {
                    jsonObject = new JSONObject(responseInfo);
                    nickname = jsonObject.getString("nickname");
                    openid = jsonObject.getString("openid");
                    LoginActivity.wechatName = nickname;
                    LoginActivity.wechatOpenid = openid;
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                finish();
                EventBus.getDefault().post(new WechatLoginEvent());
            }
        });
    }
}
